<?php


namespace ba;


use app\api\model\Member;
use app\exceptions\ApiException;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Shipping\Client;

/**
 * 订单发货信息
 */
class Order
{
    const SEND_ORDER = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info';


    /**
     * 发货
     */
    public function sendOrder($data)
    {
        $config = config('wechat');
        $date = new \DateTime();
        $formattedDate = $date->format('Y-m-d\TH:i:s.vP');
        $app = Factory::miniProgram(config('wechat.xcx'));
        //获取用户信息
        $member = (new Member())->where(['id' => $data['member_id']])->find();
        $data = [
            'order_key' => [
                'order_number_type' => 1,
                'mchid' => $config['wechat_pay']['mch_id'],
                'out_trade_no' => $data['out_trade_no']
            ],
            'logistics_type' => 1,
            'delivery_mode' => 1,
            'shipping_list' => [
                [
                    'tracking_no' => $data['express_nums'],
                    'express_company' => $data['express_name'],
                    'item_desc' => $data['land_name'] . $data['massif_name'],
                ]
            ],
            'upload_time' => $formattedDate,
            'payer' => [
                'openid' => $member['openid']
            ]
        ];

        $result = $app->shipping->uploadShippingInfo($data);
        if($result['errcode'] != 0){
            throw new Exception($result['errmsg']);
        }

        return true;
    }


    public function confirmReceive($data){
        $app = Factory::miniProgram(config('wechat.xcx'));
        $data = [
            'transaction_id' => $data['transaction_id'],
            'received_time' => time(),
        ];
        $result = $app->shipping->notifyConfirmReceive($data);
        if($result['errcode'] != 0){
            throw new ApiException('操作失败');
        }
    }
}